import { RouteRecordNormalized, RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { useSettingStore } from '@/store/setting';
import { getTitle } from '@/utils';

const settingStore = useSettingStore();

// 配置路由
const aboutRouter = {
    path: '/about',
    name: 'about',
    component: () => import('@/views/about/index.vue'),
    meta: {},
    children: []
} as RouteRecordRaw;

const modules: Record<string, any> = import.meta.glob(['./modules/*.ts'], {
    eager: true
});

// 配置路由
const routes: Array<RouteRecordRaw> = [];
Object.keys(modules).forEach((key) => {
    const module = modules[key].default;
    routes.push(module);
});

routes.push(aboutRouter);

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

const handleRouters = (currentName: string) => {
    const titles = getTitle(currentName, router.getRoutes());
    settingStore.setTitle(titles);
};

const noStatusPage = ['/login', '/about'];
router.beforeEach(async (_to, from, next) => {
    NProgress.start();
    const token = sessionStorage.getItem('userInfo');
    const userIsLogin = token ? true : false;
    if (userIsLogin || noStatusPage.includes(_to.path)) {
        next();
    } else {
        next('/login');
    }
    handleRouters(_to.name as string);
});

router.afterEach((_to) => {
    NProgress.done();
});

export default router;
